package com.adwhirl.eventadapter;

import java.lang.ref.WeakReference;
import android.app.Activity;
import android.util.Log;
import com.adwhirl.AdWhirlLayout;
import com.adwhirl.AdWhirlLayout.AdWhirlInterface;
import com.adwhirl.AdWhirlLayout.IGmOnEventAdapterChangedListener;
import com.adwhirl.eventadapter.GmAdWhirlEventAdapterData.GmEventADType;
import com.adwhirl.obj.Ration;
import com.adwhirl.util.AdWhirlUtil;

public class GmAdWhirlEventHandler implements AdWhirlInterface,
		IGmAdWhirlEventAdapter {

	

	private WeakReference<AdWhirlLayout> mAdLayoutRef = null;
	// used to control event adapter.
	private IGmAdWhirlEventAdapter mAdapter = null;

	public GmAdWhirlEventHandler(AdWhirlLayout adLayout,
			IGmOnEventAdapterChangedListener ls) {
		if (adLayout != null) {
			mAdLayoutRef = new WeakReference<AdWhirlLayout>(adLayout);
			adLayout.setAdWhirlInterface(this);
		}
		mOnEventAdapterChangedListener = ls;
	}

	private IGmOnEventAdapterChangedListener mOnEventAdapterChangedListener = null;

	public IGmOnEventAdapterChangedListener getOnEventAdapterChangedListener() {
		return mOnEventAdapterChangedListener;
	}

	public synchronized void setOnEventAdapterChangedListener(
			IGmOnEventAdapterChangedListener ls) {
		mOnEventAdapterChangedListener = ls;
	}

	@Override
	public void adWhirlGeneric() {

	}

	private void disposeAdapter() {
		if (mAdapter != null) {
			mAdapter.dispose();
			mAdapter = null;
		}
		AdWhirlLayout adLayout = mAdLayoutRef.get();
		if (adLayout != null) {
			adLayout.removeAllViews();
		}
	}

	@Override
	public void dispose() {
		disposeAdapter();
	}

	public synchronized void createEventAdapter(Ration ration) {

		AdWhirlLayout adLayout = mAdLayoutRef.get();

		if (adLayout == null) {
			return;
		}
		Activity activity = adLayout.activityReference.get();
		if (activity == null) {
			return;
		}
		String key = ration.key;
		if (key == null) {
			Log.w(AdWhirlUtil.ADWHIRL, "Event key is null");
			adLayout.rollover();
			return;
		}

		String adName = ration.name;

		if (adName.length() < 1 || key.length() < 1) {
			Log.w(AdWhirlUtil.ADWHIRL, "Event key separator not found");
			adLayout.rollover();
			return;
		}

		disposeAdapter();
		GmEventADType adType = null;
		if (mOnEventAdapterChangedListener != null) {
			mOnEventAdapterChangedListener.onEventAdapterChanged(adType);
		}
		if (adName.equals(GmEventADType.YOUMI.adName)) {
			mAdapter = new GmAdWhirlEventAdapter_cn_youmi(adLayout, ration);
		} else {
			adLayout.rollover();
		}
		return;
	}

}
